#!/usr/bin/env python
#-*- coding:UTF-8 -*-
from __future__ import unicode_literals
import os, sys, shutil, re,codecs, json
import xdrlib
import xlrd
import zipfile
import time
import platform
from PIL import Image



isformattomp4 = False
if len(sys.argv) > 1:
    if sys.argv[1] == 'yes':
        isformattomp4 = True
# 默认info的内容
info = {"type":"teaching","pages":[]}
games = []
basepath = input('请输入打包教材路径:').strip()
strokepath = "/Users/wangshan/Desktop/point"
baseurl = "http://shufa.com/"
allfile = []
convertfile = []
daorpath = os.path.join(basepath, "导入.xlsx")
fenxipath = os.path.join(basepath, "书写提要.xlsx")
jizipath = os.path.join(basepath, "集字.xlsx")
bijiaopath = os.path.join(basepath, "比较.xlsx")
biaozhupath = os.path.join(basepath, "标注.xlsx")
separator = '/'
sysstr = platform.system()
if(platform.system() =="Windows"):
   separator = '\\'
# 当前课时序号
lessonnum = 1
# 当前需要补充组件文本描述的序号
daorunum = 0

# 当前课时解读序号
bijiaonum = 0

# 分析序号
fenxinum = 0

#图片合并按照每组图片固定张数合并
groupnum = 10

#内容保存目录
newfolderpath = ""


# 将视频转码为mp4文件
def format_to_mp4(srcfile):
    dstfile = os.path.splitext(srcfile)[0] + 'old.mp4'
    shutil.move(srcfile,dstfile)
    if(platform.system() =="Windows"):
        comm = 'ffmpeg -i "{0}" -strict -2 "{1}"'.format(dstfile, srcfile)
        os.system(comm)
    else:
        comm = 'ffmpeg -i {0} -strict -2 {1}'.format(dstfile, srcfile)
        os.system(comm)
    os.remove(dstfile)

# 获取文件的扩展名
def file_extension(path):
    splits = os.path.splitext(path)
    return splits[1]


# 打开指定excel文件
def open_excel(file= 'file.xls'):
    try:
        data = xlrd.open_workbook(file)
        return data
    except valueError:
        print(valueError)

# 获取excel指定节点最后一行内容
def excel_table_byindex(file= '',row_index=1,sheet_index=0,column=-1):
    data = open_excel(file)
    table = data.sheets()[sheet_index]
    rownames =  table.row_values(row_index-1) #某一行数据
    return rownames[column]


# 传入要拼接的图片列表、拼接完成后的图片名称
def pinjie(images,savepath):
    imagefile = []
    imageheight = 0
    totalwidth = 0
    for imagepath in images:
        imageinfo = Image.open(imagepath)
        if imageheight == 0:
            imageheight = imageinfo.size[1]
        totalwidth += imageinfo.size[0]
        imagefile.append(imageinfo)
        target = Image.new('RGB', (totalwidth, imageheight))
        left = 0
    for imageinfo in imagefile:
        target.paste(imageinfo, (left, 0, left + imageinfo.size[0], imageheight))# 将image复制到target的指定位置中
        left += imageinfo.size[0] # left是左上角的横坐标，依次递增
        quality_value = 100 # quality来指定生成图片的质量，范围是0～100
        target.save(savepath, quality = quality_value)

# 原图路径、保存到的文件夹路径，返回图片列表内容：行数、列数、宽、高、图片名称
def splitimage(src, dstpath):
    img = Image.open(src)
    w, h = img.size
    rownum = int(h/256)
    colnum = int(w/256)
    if rownum == 0:
        rownum = 1
    if colnum == 0 :
        colnum = 1
    content = {}
    content["column"] = colnum
    content["row"] = rownum
    if rownum <= h and colnum <= w:
        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
        basename = fn[0]
        ext = fn[-1]
        num = 0
        images = []
        rowheight = float(h) / rownum
        colwidth = float(w) / colnum
        content["width"] = colwidth
        content["height"] = rowheight
        content["images"] = images
        for r in range(rownum):
            for c in range(colnum):
                box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
                imagename =  basename + '_' + str(r) + '_' + str(c)  + '.' + ext
                resultpath = os.path.join(dstpath,imagename)
                item = {"url":baseurl  + imagename}
                img.crop(box).save(resultpath)
                num = num + 1
                images.append(item)
    
    else:
        print('不合法的行列切割参数！')
    return content


# 在课时同级目录下创建新的文件夹
def getNewFolder(path):
    folderPath = path + "_new"
    if not  os.path.exists(folderPath):
          os.mkdir(folderPath)
    return folderPath

# 在课时同级目录下创建新的文件夹
def errorFile(path):
    if  path.find(".DS_Store") == 0 or path.find(".db") == 0:
#        print('\033[1;31;47m')
         print('错误资源:' + path)
#        print('\033[0m')

def notFoundFile(path):
#    print('\033[1;33;47m')
     print('没有找到资源:' + path)
#    print('\033[0m')


# 内容保存到指定目录下
def save(filename, contents): 
  fh = open(filename, 'w',encoding="utf-8")
  fh.write(contents)
  fh.close()

def convert_char_json(src_file):
    if  os.path.exists(src_file):
        temp_file = src_file + "_new"
        shutil.copy(src_file, temp_file)
        text = codecs.open(temp_file, 'r', 'utf-16-le').read()
        f = open(src_file, 'w')
        f.write(text)
        f.close()
        os.remove(temp_file)

# 获取images列表
def images(filelist,path):
    images = []
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                images.append({"url":baseurl  + filename})
                allfile.append(filepath)
    return images

# 获取目录下文件，并按照名称排序
def fzlistdir(path):
    filelist =  os.listdir(path)
    newfilelist = []
    for f in filelist:
        if not f.startswith('.'):
            newfilelist.append(f)
    return sorted(newfilelist)


# 遍历指定目录，显示目录下的所有文件名
def dirlist(path):
    print(path)
    global lessonnum
    global daorunum
    global bijiaonum
    global fenxinum
    global games
    global newfolderpath
    print('\033[1;31;40m')
    print('*' * 50)
    print('打包开始')
    print('\033[0m')
# 创建本地测试的文件夹
    parcketPath = path + "_本地测试"
    print(parcketPath)
    if os.path.exists(parcketPath):
        shutil.rmtree(parcketPath)
    os.mkdir(parcketPath)

# 创建线上上传的文件夹
    onlinePath  = path + "_上线"
    if  os.path.exists(onlinePath):
          shutil.rmtree(onlinePath)
    os.mkdir(onlinePath)

    filelist =  fzlistdir(path)
    for lessonfoldername in filelist:
        filepath = os.path.join(path, lessonfoldername)
        if os.path.isdir(filepath):
            print("打包目录:" + filepath)
            print ("打包中............")
            info["pages"] = []
            games = []
            del allfile[:]
            del convertfile[:]
            num  =  lessonfoldername.split('.')[0]
            lessonname = lessonfoldername.split('.')[1]
            lessonnum = int(num)
            daorunum = 0
            bijiaonum = 0
            fenxinum = 0
            newfolderpath = getNewFolder(filepath)
            lesson(filepath)
            # 拷贝所有找到的文件，拷贝到新创建的文件夹下
            for oldpath in allfile:
                newpath =  os.path.join(newfolderpath,oldpath.split(separator)[-1])
                if not newpath.find(".DS_Store") > 0: 
                    shutil.copy(oldpath, newpath)
                    if isformattomp4:
                        if file_extension(newpath) == '.mp4' or file_extension(newpath) == '.MP4':
                            format_to_mp4(newpath)
            for charname in convertfile:
                charpath = os.path.join(newfolderpath,charname)
                if os.path.exists(charpath):
                    convert_char_json(charpath)
                else:
                    notFoundFile(charpath)
            save(os.path.join(newfolderpath,"info.json"),json.dumps(info,ensure_ascii=False))
            for game in games:
                gamefilename = game["filename"]
                gamecontent = game["content"]
                save(os.path.join(newfolderpath,gamefilename),json.dumps(gamecontent,ensure_ascii=False))
            lessonfolder =  os.path.join(onlinePath,str(lessonnum))
            if os.path.exists(lessonfolder):
                shutil.rmtree(lessonfolder)
            os.mkdir(lessonfolder)
            zipname = lessonname + ".zip"
            z = zipfile.ZipFile(os.path.join(lessonfolder,zipname), 'w', zipfile.ZIP_DEFLATED)
            for dirpath, dirnames, filenames in os.walk(newfolderpath):
                for filename in filenames:
                    z.write(os.path.join(dirpath,filename),filename)
            z.close()
            shutil.move(newfolderpath,parcketPath + "/" +lessonfoldername)
    print('\033[1;31;40m')
    print ('打包结束')
    print('*' * 50)
    print('\033[0m')


# 解析课时内容
def lesson(path):
    filelist =  fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            if filename[0] == "p":
                info["pages"].append(page(filepath))
            else:
                 print (filepath + " " + "不是有效的一级目录文件夹")
        elif filepath.find(".mp4") > 0:
            allfile.append(filepath)
            info["zixiuUrl"] = baseurl  + filename

#解析一级目录
def page(path):
    filelist =  fzlistdir(path)
    foldername = os.path.normcase(path).split(separator)[-1]
    page = {"title":foldername.split("_")[-1],"ID":foldername.split("_")[0].lstrip('p')}
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            if filename[0] == "s":
                if not "subMenus" in page:
                    page["subMenus"] = []
                page["subMenus"].append(submenu(filepath))
            elif filename[0] == "c":
                if not "components" in page:
                    page["components"] = []
                page["components"].append(component(filepath))
            else:
                 print (filepath + " " + "不是有效的二级目录或者组件文件夹")
    return page             

#解析二级目录
def submenu(path):
    filelist =  fzlistdir(path)
    foldername = os.path.normcase(path).split(separator)[-1]
    submenu =  {"title":foldername.split("_")[-1]}
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            if filename[0] == "c":
              if not "components" in submenu:
                    submenu["components"] = []       
              submenu["components"].append(component(filepath)) 
            else:
                 print(filepath + " " + "不是有效的组件文件夹")
    return submenu

# 解析组件
def component(path):
    foldername = os.path.normcase(path).split(separator)[-1]
    componentType  = foldername.split("_")[-1]
    component = {"type":componentType}
    if componentType == "daoru"  or componentType == "jiangjie":
         daoru(path,component)
    elif componentType == "yunbi" or componentType == "lizi" or componentType == "jubu" :
         image(path,component)
    elif componentType == "shifan":
         shifan(path,component)
    elif componentType == "dutie":
         dutie(path,component)   
    elif componentType == "bihua":
         bihua(path,component)          
    elif componentType == "yanbian" or componentType == "jiexi" or componentType == "donghua" or componentType == "zhishidian" or componentType == "fanzi" or componentType == "wenhua":
         video(path,component) 
    elif componentType == "jizi":
         jizi(path,component)   
    elif componentType == "guancha":
         guancha(path,component)  
    elif componentType == "renshi" :
         renshi(path,component)
    elif componentType == "bijiao" or componentType == "guangdu" or componentType == "shendu":
         bijiao(path,component)
    elif componentType == "fenxi":
         fenxi(path,component)  
    elif componentType == "jiedu" or componentType == "lianxi":
         jiedu(path,component)  
    elif componentType == "biaozhu":
         biaozhu(path,component)  
    elif componentType == "dutie2":
         dutie2(path,component)
    elif componentType == "shizi":
        shizi(path,component)
    elif componentType == "xiaomaodiaoyu":
        xiaomaodiaoyu(path,component)
    elif componentType == "shangxi":
        shangxi(path,component)
    elif componentType == "jianjie":
        jianjie(path,component)
    elif componentType == "shiwen":
        shiwen(path,component)
    elif componentType == "danzi":
        danzi(path,component)
    elif componentType == "hudong":
        hudong(path,component)
    elif componentType == "xiangyixiang":
        xiangyixiang(path,component)
    elif componentType == "zuzi":
        zuzi(path,component)
    else:
        print("无效的组件" + componentType)
    return component

 # 导入、讲解
def daoru(path,component):
    filelist = fzlistdir(path)
    component["images"] = []
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            allfile.append(filepath)
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["images"].append({"url":baseurl  + filename,"startTime":int(filename.split("_")[-1][:-4])})
            elif filepath.find(".mp3") > 0 or filepath.find(".mp4") > 0:
                component["backgroundMusicUrl"] = baseurl  + filename
    if not "backgroundMusicUrl" in component:
            print(path + "没有背景音乐")

 # 运笔 、例子、赏析、释文、局部
def image(path,component):
    filelist = fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["url"] = baseurl  + filename
                allfile.append(filepath)
            else:
                errorFile(filepath)

 # 示范
def shifan(path,component):
    filelist = fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".mp4") > 0: 
                if filepath[-5] == "侧":
                    component["title"] = "﹃" + filename[:-5] +"﹄"
                    component["leftUrl"] = baseurl  + filename
                    allfile.append(filepath)
                elif filepath[-5] == "顶":
                    component["topUrl"] = baseurl  + filename
                    allfile.append(filepath)
                else:
                    component["title"] = "﹃" + filename[:-4] +"﹄"
                    component["leftUrl"] = baseurl  + filename
                    allfile.append(filepath)
 # 读帖
def dutie(path,component):
    filelist = fzlistdir(path)
    component["images"] = []
    character = path.split(separator)[-2].split("_")[-1]
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not filepath.find(".DS_Store") > 0: 
            if os.path.isdir(filepath):
                struct = filename.split('_')[-1]
                imageInfo = {"title":struct}
                component["images"].append(imageInfo)
                imagelist = os.listdir(filepath)
                for imagename in imagelist:
                    if imagename.find(".png") > 0 or imagename.find(".jpg") > 0:
                        imagepath = os.path.join(filepath,imagename)
                        if imagename.find("原帖.png") > 0:
                            if not "originalUrl" in imageInfo:
                                imageInfo["originalUrl"] = baseurl  + imagename
                                allfile.append(imagepath)
                            else:
                                errorFile(imagepath)
                        else:
                            if not "url" in imageInfo:
                                imageInfo["url"] = baseurl  + imagename
                                allfile.append(imagepath)
                            else:
                                 errorFile(imagepath)
                
                    else:
                         errorFile(os.path.join(filepath,imagename))

 # 笔画
def bihua(path,component):
    filelist = fzlistdir(path)
    character = path.split(separator)[-2].split("_")[-1]
    filename =  character.encode('unicode_escape').decode()[2:] + ".json"
    filepath = os.path.join(strokepath, filename)
    component["url"] = baseurl  + filename
    if os.path.exists(filepath):
         allfile.append(filepath)
         if not filename in convertfile:
            convertfile.append(filename)
    else:
        notFoundFile(filename) 
 # 演变、动画
def video(path,component):
    filelist = fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".mp4") > 0: 
                component["url"] = baseurl  + filename
                allfile.append(filepath)
            else:
                errorFile(filepath)    

 # 集字  
def jizi(path,component):
    filelist = fzlistdir(path)
    component["text"] = excel_table_byindex(jizipath,lessonnum,0)
    component["images"] = images(filelist,path)

 # 观察  
def guancha(path,component):
    global daorunum
    daorunum += 1
    filelist = fzlistdir(path)
    component["annotation"] =  excel_table_byindex(daorpath,lessonnum,0,daorunum)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            allfile.append(filepath)
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["imageUrl"] = baseurl  + filename
        else:
            if os.path.normcase(filepath).split(separator)[-1] == "images":
                imagelist = os.listdir(filepath)
                component["images"] = images(imagelist,filepath)
           
 # 认识  
def renshi(path,component):
    filelist = fzlistdir(path)
    images = []
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                images.append({"url":baseurl  + filename,"annotation":filename.split('_')[-1][0:-4]})
                allfile.append(filepath)
    component["images"] = images

# 比较
def bijiao(path,component):
    filelist = fzlistdir(path)
    global bijiaonum
    bijiaonum += 1
    images = []
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            print(filepath)
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                images.append({"url":baseurl  + filename,"annotation":filename.split('_')[-1][0:-4]})
                allfile.append(filepath)
    component["images"] = images
    text = excel_table_byindex(bijiaopath,lessonnum,0,bijiaonum)
    if len(text) > 0 :
        component["text"] = text
 #  分析  
def fenxi(path,component):
    filelist = fzlistdir(path)
    global fenxinum
    fenxinum += 1
    component["annotation"] = excel_table_byindex(fenxipath,lessonnum,0,fenxinum)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["imageUrl"] = baseurl  + filename
                allfile.append(filepath)
 

 #  解读  
def jiedu(path,component):
    filelist = fzlistdir(path)
    global daorunum
    daorunum += 1
    component["annotation"] = excel_table_byindex(daorpath,lessonnum,0,daorunum)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                if filepath[-5] == "左":
                    component["leftImageUrl"] = baseurl  + filename
                    allfile.append(filepath)
                elif filepath[-5] == "中":
                    component["middleImageUrl"] = baseurl  + filename
                    allfile.append(filepath)
                elif filepath[-5] == "右":
                    component["rightImageUrl"] = baseurl  + filename
                    allfile.append(filepath)           
                else:
                    errorFile(filepath)

 #  标注 
def biaozhu(path,component):
    filelist = fzlistdir(path)
    component["images"] = []
    component["text"] = excel_table_byindex(biaozhupath,lessonnum,0)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not filepath.find(".DS_Store") > 0: 
            if os.path.isdir(filepath):
                imagelist = os.listdir(filepath)
                imageinfo = {}
                component["images"].append(imageinfo)
                for imagename in imagelist:
                    imagepath = os.path.join(filepath, imagename)
                    if imagepath.find(".png") > 0 or imagepath.find(".jpg") > 0:
                        if imagepath.find("标注") > 0: 
                            imageinfo["markUrl"] = baseurl  + imagename
                        else:
                            imageinfo["url"] = baseurl  + imagename
                        allfile.append(imagepath)
                    else:
                        errorFile(imagepath)    

 #  读帖2
def dutie2(path,component):
    filelist = fzlistdir(path)
    global daorunum
    daorunum += 1
    component["text"] = excel_table_byindex(daorpath,lessonnum,0,daorunum)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["url"] = baseurl  + filename
                allfile.append(filepath)

 #  识字
def shizi(path,component):
    filelist = fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["imageUrl"] = baseurl  + filename
                allfile.append(filepath)
            elif filepath.find(".mp3") > 0:
                component["musicUrl"] = baseurl  + filename
                allfile.append(filepath)
        else:
            component["images"] = []
            imagelist = os.listdir(filepath)
            for imagename in imagelist:
                imagepath = os.path.join(filepath, imagename)
                imageinfo = {}
                if imagepath.find(".png") > 0 or imagepath.find(".jpg") > 0:
                    imageinfo["url"] = baseurl  + imagename
                    allfile.append(imagepath)
                    component["images"].append(imageinfo)
    if not "imageUrl" in component:
        print(path + "没有图片")
    if not "musicUrl" in component:
        print(path + "没有音频")
    if not "images" in component:
        print(path + "没有序列图")

#  小猫钓鱼
def xiaomaodiaoyu(path,component):
    filelist = fzlistdir(path)
    xiaomaodiaoyu = []
    for foldername in filelist:
        folderpath = os.path.join(path, foldername)
        if os.path.isdir(folderpath):
            items = []
            xiaomaodiaoyu.append(items)
            imagelist = os.listdir(folderpath)
            for imagename in imagelist:
                imagepath = os.path.join(folderpath, imagename)
                item = {}
                items.append(item)
                if imagepath.find(".png") > 0 or imagepath.find(".jpg") > 0:
                    allfile.append(imagepath)
                    item["url"] = imagename
                    if imagepath.find("正确") > 0:
                        item["correct"] = True
                    else:
                        item["correct"] = False
    gamefilename = "xiaomaodiaoyu.json"
    component["url"] = baseurl  + gamefilename
    game = {"filename":gamefilename,"content":xiaomaodiaoyu}
    games.append(game)


#  赏析
def shangxi(path,component):
    filelist = fzlistdir(path)
    for foldername in filelist:
        folderpath = os.path.join(path, foldername)
        if os.path.isdir(folderpath):
            component["title"] = foldername
            imagelist = os.listdir(folderpath)
            imagelist.sort(reverse=True)
            images = []
            joinimages = []
            num = 0
            print('开始处理图片, 请稍候...')
            pintupath = os.path.join(folderpath,'拼图')
            if os.path.exists(pintupath):
                shutil.rmtree(pintupath)
            os.mkdir(pintupath)
            for imagename in imagelist:
                imagepath = os.path.join(folderpath, imagename)
                if imagepath.find(".png") > 0 or imagepath.find(".jpg") > 0:
                    images.append(imagepath)
                    if len(images)%groupnum == 0: #按组把图片拼接成一组大图
                        imagename =  str(num) +'.jpg'
                        savepath = os.path.join(pintupath,imagename)
                        pinjie(images,savepath)
                        num += 1
                        images = []
                        joinimages.append(savepath)
                    if len(images) > 0:
                        imagename =  str(num) +'.jpg'
                        savepath = os.path.join(pintupath,imagename)
                        pinjie(images,savepath)
                        num += 1
                        images = []
                        joinimages.append(savepath)
            imagename =  foldername +'.jpg'
            pinttuimagepath = os.path.join(pintupath,imagename)
            pinjie(joinimages,pinttuimagepath)
            component["content"] = splitimage(pinttuimagepath,newfolderpath)
            shutil.rmtree(pintupath)


#  简介
def jianjie(path,component):
    folderlist = fzlistdir(path)
    for foldername in folderlist:
        folderPath = os.path.join(path, foldername)
        if os.path.isdir(folderPath):
            component["parts"] = []
            component["title"] = foldername
            partlist = os.listdir(folderPath)
            for partfolder in partlist:
                partpath = os.path.join(folderPath, partfolder)
                if os.path.isdir(partpath):
                    part = {}
                    pos = partfolder.index("_")
                    part["title"] = partfolder[pos+1:]
                    part["elements"] = []
                    component["parts"].append(part)
                    elementfolderlist = os.listdir(partpath)
                    for elementfoldername in elementfolderlist:
                        elementfolderpath = os.path.join(partpath, elementfoldername)
                        if os.path.isdir(elementfolderpath):
                            elementlist = os.listdir(elementfolderpath)
                            item = {}
                            part["elements"].append(item)
                            if elementfoldername.find("_") > 0:
                                    pos = elementfoldername.index("_")
                                    item["title"] = elementfoldername[pos+1:]
                            for filename in elementlist:
                                filepath = os.path.join(elementfolderpath, filename)
                                if filename.find(".png") > 0 or filename.find(".jpg") > 0:
                                    allfile.append(filepath)
                                    if filepath.find("small") > 0:
                                        item["thumbImageUrl"] = baseurl  + filename
                                    else:
                                        item["imageUrl"] = baseurl  + filename
                                        if filepath.find("图") > 0:
                                            item["comments"] = filename[:-4]
                                elif filename.find(".txt") > 0 :
                                    text = ""
                                    f = open(filepath,"rt", encoding="utf-8")
                                    try:
                                        for line in f:
                                            text = text + line
                                    finally:
                                        f.close()
                                    item["text"] = text
                                else:
                                    errorFile(filepath)
                elif partfolder.find(".mp3") > 0:
                    component["musicUrl"] = baseurl  + partfolder
                    musicpath = os.path.join(folderPath, partfolder)
                    allfile.append(musicpath)

#  释文
def shiwen(path,component):
    folderlist = fzlistdir(path)
    for foldername in folderlist:
        folderPath = os.path.join(path, foldername)
        if os.path.isdir(folderPath):
            component["title"] = foldername
            component["elements"] = []
            imagesfolder = os.path.join(folderPath, "images")
            shiwenexcel = os.path.join(folderPath, "释文.xlsx")
            if not  os.path.exists(imagesfolder):
                notFoundFile(imagesfolder)
                return
            if not  os.path.exists(shiwenexcel):
                notFoundFile(shiwenexcel)
                return
            elementlist = os.listdir(imagesfolder)
            index = 1
            for filename in elementlist:
                filepath = os.path.join(imagesfolder, filename)
                if filename.find(".png") > 0 or filename.find(".jpg") > 0:
                    element= {}
                    component["elements"].append(element)
                    element["imageUrl"] = baseurl  + filename
                    element["text"] =  excel_table_byindex(shiwenexcel,index,0)
                    allfile.append(filepath)
                    index = index + 1



#  单字
def danzi(path,component):
    filelist = fzlistdir(path)
    component["images"] = []
    for foldername in filelist:
        folderpath = os.path.join(path, foldername)
        if not folderpath.find(".DS_Store") > 0:
            if os.path.isdir(folderpath):
                imagelist = os.listdir(folderpath)
                imageinfo = {}
                component["images"].append(imageinfo)
                for filename in imagelist:
                    fullpath = os.path.join(folderpath, filename)
                    if fullpath.find(".png") > 0 or fullpath.find(".jpg") > 0:
                        imageinfo["url"] = baseurl  + filename
                        allfile.append(fullpath)
                    elif fullpath.find(".mp4") > 0 :
                        if fullpath[-5] == "侧":
                            imageinfo["leftVideoUrl"] = baseurl  + filename
                            allfile.append(fullpath)
                        elif fullpath[-5] == "顶":
                            imageinfo["topVideoUrl"] = baseurl  + filename
                            allfile.append(fullpath)
                        else:
                            imageinfo["leftVideoUrl"] = baseurl  + filename
                            allfile.append(fullpath)
                    else:
                        errorFile(fullpath)
                if not "url" in imageinfo:
                    print(folderpath + "没有图片")
                if not "leftVideoUrl" in imageinfo:
                    print(folderpath + "没有视频")


#  互动
def hudong(path,component):
    filelist = fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                    allfile.append(filepath)
                    if filepath.find("正确") > 0 :
                        component["imageUrl"] = baseurl  + filename
                    else:
                        component["wrongImageUrl"] = baseurl  + filename
        else:
            component["options"] = []
            imagelist = os.listdir(filepath)
            for imagename in imagelist:
                imagepath = os.path.join(filepath, imagename)
                if imagepath.find(".png") > 0 or imagepath.find(".jpg") > 0:
                    imageinfo = {}
                    component["options"].append(imageinfo)
                    imageinfo["imageUrl"] = baseurl  + imagename
                    allfile.append(imagepath)
    if not "imageUrl" in component:
        print(path + "没有正确图片")
    if not "wrongImageUrl" in component:
        print(path + "没有错误图片")
    if not "options" in component:
        print(path + "没有选项")

#  组字
def zuzi(path,component):
    filelist = fzlistdir(path)
    zuzipath = os.path.join(path, "zuzi")
    imagepath = os.path.join(path, "animations")
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if not os.path.isdir(filepath):
            if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                component["bushouUrl"] = baseurl  + filename
                allfile.append(filepath)

    if os.path.isdir(imagepath):
        filelist = fzlistdir(imagepath)
        component["animations"] = []
        for filename in filelist:
            filepath = os.path.join(imagepath, filename)
            if not os.path.isdir(filepath):
                if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                    imageurl = baseurl  + filename
                    allfile.append(filepath)
                    component["animations"].append(imageurl)
    else:
        print(path + "没有动画")
    
    if os.path.isdir(zuzipath):
        folders = fzlistdir(zuzipath)
        component["images"] = []
        for foldername in folders:
            zuzi = os.path.join(zuzipath,foldername)
            if os.path.isdir(zuzi):
                item = {}
                component["images"].append(item)
                filelist = fzlistdir(zuzi)
                for filename in filelist:
                    filepath = os.path.join(zuzi, filename)
                    if not os.path.isdir(filepath):
                        if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
                            allfile.append(filepath)
                            imageurl = baseurl  + filename
                            if filename.find("正确") > 0:
                                item["zuziUrl"] = imageurl
                            else:
                                item["url"] = imageurl

    else:
        print(path + "没有组字")


#  想一想
def xiangyixiang(path,component):
    filelist = fzlistdir(path)
    for filename in filelist:
        filepath = os.path.join(path, filename)
        if filepath.find(".png") > 0 or filepath.find(".jpg") > 0:
            if filepath.find("标注") > 0:
                component["markUrl"] = baseurl  + filename
            else:
                component["url"] = baseurl  + filename
            allfile.append(filepath)
        elif filepath.find(".txt") > 0 :
            text = ""
            f = open(filepath,"rt", encoding="utf-8")
            try:
                for line in f:
                    text = text + line
            finally:
                f.close()
            component["text"] = text
        else:
            errorFile(filepath)


if __name__ == '__main__':
    dirlist(basepath)




